import serial

BAUDRATE = 9600

def createFile(name):
    file = open(name + ".csv", "w")
    file.write("Red,Green,Blue,Clear,RedCap,GreenCap,BlueCap\n")
    return file

def measure(file):
    port.write('Q')
    m = port.readline()
    m = m.rstrip('\r\n')
    file.write(m + '\n')
    print m
	
if __name__ == "__main__":
    port = serial.Serial("COM3", BAUDRATE)
    print "Connection opened."

    # Handshake
    port.write('A')
    print "Handshake completed"
    
    num_measurements = 50
    colors = ['R', 'G', 'B']
    
    while(1):
        fileName = raw_input()
        cmd = fileName[0]
        
        if (cmd == 'X'):
            break
        
        if (cmd == 'D' or cmd == 'L'):
            port.write(cmd)
            continue
        
        file = createFile(fileName)
        for cap in xrange(16):
            if (cap >= 10):
                value = '00'
            else:
                value = '000'
                
            value += str(cap)
            
            for color in colors:
                port.write('C')
                port.write(color)
                port.write(value)
              
            for i in xrange(num_measurements):
                measure(file)
                  
        file.close()
        print "End"
        
    port.close()
